/**
 * 取件页面专用 - 验证存件码接口
 * 
 * 接口说明：
 * - 用于取件页面验证存件码
 * - 需要携带token进行身份验证
 * - 需要传递存件码作为路径参数
 * - 虽然与存件页面使用相同接口，但为了代码清晰性单独存放
 */

import { API_BASE_URL, getHeaders } from '../config'
import type { ApiResponse } from '../types/common'
import type { StorageDetailResponseData } from '../types/storage'

/**
 * 取件页面专用 - 验证存件码接口
 * 
 * @param storeCode 存件码
 * @returns Promise<ApiResponse<StorageDetailResponseData>>
 * 
 * @example
 * ```typescript
 * // 请求示例
 * const storeCode = "CJ20250930172248-20" // 存件码
 * 
 * try {
 *   const response = await getPickupStorageDetail(storeCode)
 *   console.log('获取存件详情成功:', response.data)
 *   console.log('存件码:', response.data.code)
 *   console.log('存件状态:', response.data.status)
 *   console.log('过期时间:', response.data.expireTime)
 *   console.log('二维码:', response.data.qrCode)
 * } catch (error) {
 *   console.error('获取存件详情失败:', error)
 * }
 * ```
 * 
 * @example
 * ```typescript
 * // 成功响应示例
 * {
 *   "code": 200,
 *   "msg": "获取存件详情成功",
 *   "data": {
 *     "id": 60,
 *     "code": "CJ20250930172248-20",
 *     "name": "12",
 *     "description": "12",
 *     "status": 0,
 *     "createTime": "2025-09-30 17:22:48",
 *     "expireTime": "2025-10-01 17:22:49",
 *     "statusRecords": [
 *       {
 *         "createBy": "233",
 *         "createTime": "2025-09-30 17:22:48",
 *         "updateBy": null,
 *         "updateTime": null,
 *         "remark": null,
 *         "statusId": 60,
 *         "storageId": 60,
 *         "status": null,
 *         "statusDesc": "未存件",
 *         "statusTime": "2025-09-30 17:22"
 *       }
 *     ],
 *     "teacherName": "虎敏 (学生活动中心)",
 *     "qrCode": "..."
 *   }
 * }
 * ```
 * 
 * @example
 * ```typescript
 * // 失败响应示例
 * {
 *   "code": 404,
 *   "msg": "存件记录不存在",
 *   "data": null
 * }
 * ```
 * 
 * @example
 * ```typescript
 * // 认证失败响应示例
 * {
 *   "code": 401,
 *   "msg": "未授权访问，请先登录",
 *   "data": null
 * }
 * ```
 */
export const getPickupStorageDetail = async (storeCode: string): Promise<ApiResponse<StorageDetailResponseData>> => {
  try {
    // 验证参数
    if (!storeCode || storeCode.trim() === '') {
      throw new Error('存件码不能为空')
    }

    const response = await fetch(`${API_BASE_URL}/api/storage/validate/${storeCode}`, {
      method: 'GET',
      headers: getHeaders(), // 自动携带token
    })

    if (!response.ok) {
      if (response.status === 401) {
        throw new Error('未授权访问，请先登录')
      }
      if (response.status === 404) {
        throw new Error('存件记录不存在')
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result: ApiResponse<StorageDetailResponseData> = await response.json()
    
    if (result.code !== 200) {
      throw new Error(result.msg || '获取存件详情失败')
    }

    return result
  } catch (error) {
    console.error('取件页面获取存件详情接口调用失败:', error)
    throw error
  }
}
